/*
 * Copyright (C) 2013 Daniel Wasilew <daniel.wasilew@codeminer.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.codeminer.parts.library;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 *
 * @author Daniel Wasilew <daniel.wasilew@codeminer.org>
 */
public class Artwork {

    public static Artwork fromFile(File file) {
        FileInputStream fis = null;
        try {
            byte[] buff = new byte[(int) file.length()];
            fis = new FileInputStream(file);
            fis.read(buff);
            fis.close();
            return new Artwork(buff);
        } catch (IOException ex) {
            LoggerFactory.getLogger(Artwork.class).error("could not read artwork file", ex);
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException ex) {
                LoggerFactory.getLogger(Artwork.class).error("could not read artwork file", ex);
            }
        }

        return null;
    }
    private final String md5;
    private byte[] artworkData;

    public Artwork(byte[] artworkData) {
        this.artworkData = artworkData.clone();
        this.md5 = DigestUtils.md5Hex(artworkData);
    }

    public String getMd5() {
        return md5;
    }

    public byte[] getData() {
        return this.artworkData;
    }

    public boolean writeToFolder(File folder) {
        File file = new File(folder, md5);
        if (file.exists()) {
            return true;
        }

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(artworkData);
            return true;
        } catch (IOException ex) {
            LoggerFactory.getLogger(Artwork.class).error("could not write artwork to disk", ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    LoggerFactory.getLogger(Artwork.class).error("could not close fos", ex);
                }
            }
        }
        return false;
    }
}
